package com.gccloud.dataroom.service;

import com.gccloud.common.permission.IApiPermissionService;
import com.mes.common.core.context.SecurityContextHolder;
import com.mes.common.core.text.Convert;
import com.mes.common.core.utils.JwtUtils;
import com.mes.common.security.utils.SecurityUtils;
import com.mes.system.api.model.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dataroom
 * @version 1.0
 * @date 2023/10/20 10:26
 */
@Service
public class PermissionServiceImpl implements IApiPermissionService {

    /**
     * 获取用户名称
     */
    public String getUserName()
    {
        return reBuildLoginUser(SecurityUtils.getToken()).getUsername();
    }

    @Override
    public boolean verifyApiPermission(HttpServletRequest request, String... permission) {
        // 获取当前用户的权限
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String token = SecurityUtils.getToken();
        if (loginUser == null){
            loginUser = reBuildLoginUser(token);
        }
        System.out.println("loginUser:" + loginUser);
        System.out.println(loginUser.getPermissions());
        Set<String> permissions = loginUser.getPermissions();
        if (Objects.equals(loginUser.getUsername() , "admin")){
            permissions  = Collections.singleton("*:*:*");
        }
        if (permissions.contains("*:*:*")) {
            // 若依的全部权限标识
            return true;
        }
        // 判断当前用户是否拥有对应的权限
        for (String s : permission) {
            if (!permissions.contains(s)) {
                return false;
            }
        }
        // 返回值true标识校验通过
        return true;
    }

    private LoginUser reBuildLoginUser(String token) {
        Claims claims = JwtUtils.parseToken(token);
        if (claims == null) return null;
        LoginUser loginUser = new LoginUser();

        // 设置基础字段
        loginUser.setToken(token);
        loginUser.setUsername(JwtUtils.getUserName(claims));
        loginUser.setUserid(Convert.toLong(JwtUtils.getUserId(claims), -1L));

        // 可选：从 claims 中提取权限集合（需确保 token 中包含 permissions 字段）
        Object perms = claims.get("permissions");
        if (perms instanceof List<?>) {
            loginUser.setPermissions((Set<String>) ((List<?>) perms).stream().map(Object::toString).collect(Collectors.toSet()));
        }

        // 可选：填充 SysUser（若后续业务需要）
//        SysUser sysUser = new SysUser();
//        sysUser.setUserId(loginUser.getUserid());
//        sysUser.setUserName(loginUser.getUsername());
//        loginUser.setSysUser(sysUser);

        return loginUser;
    }
}


